/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapplication;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static serverapplication.GlobalVariables.*;

/**
 *
 * @author 王舒嶷
 */
public class WebService implements Runnable {

    public WebService(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
        try {
            in = new Scanner(socket.getInputStream());
            out = new PrintWriter(socket.getOutputStream());
            doService();
        } catch (IOException ex) {
            Logger.getLogger(WebService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                socket.close();
            } catch (IOException ex) {
                Logger.getLogger(WebService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void doService() throws IOException {
        while (true) {
            if (!in.hasNext()) {
                return;
            }
            String command = in.next();
            if (command.equalsIgnoreCase("QUIT")) {
                return;
            } else {
                executeCommand(command);
            }
        }
    }
    
    private void executeCommand(String command){
        if(command.equalsIgnoreCase("VoteQuestion")){
            boolean success=false;
            int question_id=in.nextInt();
            int user_id=in.nextInt();
            // read a psudo-line
            String ans=in.nextLine();
            ans=in.nextLine();
            globalVariableLock.lock();
            try{
                if(questionInVoting.containsKey(question_id)){// the question already started voting
                    questionInVoting.get(question_id).chooseAns(user_id, ans);
                    success=true;
                }else{// the question has not been started yet
                    success=false;
                }
            }finally{
                globalVariableLock.unlock();
            }
            out.println(success);
            out.flush();
        }
    }

    // instance fields
    private Socket socket;
    private Scanner in;
    private PrintWriter out;
}
